import pandas as pd
from factor_analyzer import factor_analyzer,Rotator
import numpy as np

data = pd.read_excel('聚类.xls')

fa = factor_analyzer.FactorAnalyzer(16, rotation=None)
fa.fit(data)

def outputResult(fa,data,path):
    print('因子载荷矩阵:')
    print(fa.loadings_)
    print('解释方差：')
    var=fa.get_factor_variance()
    var=np.array(var)
    print(var)
    valu=fa.transform(data)
    valu=np.array(valu)
    np.savetxt(path, valu, delimiter=',')
    print('因子得分文件已保存')

print('KMO:')
print(factor_analyzer.calculate_kmo(data))
print('Bartlett:')
print(factor_analyzer.calculate_bartlett_sphericity(data))
outputResult(fa,data,'未旋转因子得分.csv')

ev = fa.get_eigenvalues()
ev = ev[0]

# 看哪些因子可用（结果1-5）
featureNum=1
for i in ev:
    if i>1:
        print(featureNum)
    featureNum+=1

fa = factor_analyzer.FactorAnalyzer(16, rotation='oblimin') # 正交旋转
fa.fit(data)
outputResult(fa,data,'旋转因子得分.csv')